﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Text;
using System.Data;

using CooWork.Models;
using CooWork.Core;
using Coowork.Data.Mapping;

namespace CooWork.Services
{
    public class TaskService:ITaskService
    {
        private CooWorkEntities context = new CooWorkEntities();


        public Dictionary<int,TreeNode> GetCDepartment(int cid)
        {
            Dictionary<int, TreeNode> gcd = new Dictionary<int, TreeNode>();

            var ld = context.Departments.Where(x => x.cid == cid).ToList();

            ld.ForEach(x => gcd.Add(x.ID, new TreeNode((x.parentId.HasValue?x.parentId.Value.ToString()+"_":"")+x.DepartmentName, x.DepartmentName, x.ID, x.parentId, true)));

            return gcd;
        }







        public void delDepartment(TreeNode tnode, ref Dictionary<int, TreeNode> ld, int cid)
        {
            List<int> li = new List<int>();
            tnode.allkeys(tnode, li);
            var li2 = ld.Keys.ToList();
            var liexp = li2.Except(li);

            string ids = string.Empty;
            if (liexp.Count() > 0)
            {
                foreach (int i in liexp)
                {
                    ids += i.ToString()+ ",";
                }
                ids = ids.Trim(',');
                DataProvider.ExecuteNonQuery("delete from [Department] where ID in (" + ids + ") and cid =" +cid);
            }            

        }


        public void updateDepartment(TreeNode tnode, ref  Dictionary<int, TreeNode> ld ,int cid)
        {
            string sql = "update [Department] set ";
            if (tnode.Did > 0)
            {            
                if (tnode.Tname != ld[tnode.Did].Tname)
                {
                    sql += " DepartmentName=" + tnode.Tname + " ,";
                }

                if (tnode.ParentId.HasValue&&tnode.ParentId != ld[tnode.Did].ParentId)
                {
                    sql += " parentId=" + tnode.ParentId + " ,";
                }
            }
            if (sql.Contains("="))
            {
                sql = sql.Trim(',');
                sql += " where cid=" + cid + " and ID=" + tnode.Did;
                DataProvider.ExecuteNonQuery(sql);
            }

            if (tnode.Did == 0)
            {
                sql = "insert into [Department](DepartmentName,parentId,cid) values('{0}',{1},{2}) select @@identity";
                sql = string.Format(sql, tnode.Tname, tnode.ParentId, cid);
                DataTable dt = DataProvider.GetDataTable(sql);
                tnode.Did = Convert.ToInt32(dt.Rows[0][0]);
                if (tnode.Count > 0)
                {
                    foreach (TreeNode t in tnode.Children)
                    {
                        t.ParentId = tnode.Did;                        
                    }
                }
            }

            if (tnode.Count > 0)
            {
                foreach (TreeNode t in tnode.Children)
                {
                    updateDepartment(t, ref ld, cid);
                }
            }


        }   
        
        public string updateWatchers(List<string> tminus, List<string> tplus, int taskId)
        {

            string sql = string.Empty;
            StringBuilder tlist = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            int cid = UserService.UcId();

            if (tminus.Count > 0)
            {
                sql = "delete from [CooWatchlist] where cid={0} and  taskId={1} and Observer in ({2})";
                foreach (string s in tminus)
                {
                    tlist.AppendFormat("'{0}',", s);
                }
                sql = string.Format(sql, cid, taskId, tlist.ToString().Trim(','));
            }

            foreach (string s in tplus)
            {
                sb.AppendFormat("insert into [CooWatchlist](taskId,Observer,cid) values({0},'{1}',{2})", taskId, s, cid);
            }

            sb.AppendFormat(" select Observer  from [CooWatchlist] where cid={0} and taskId={1}", cid, taskId);
            sql = sql + sb.ToString();
            DataTable dt = DataProvider.GetDataTable(sql);
            string ret = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                ret += "," + dr["Observer"].ToString();
            }
            return ret.Trim(',');

        }



        public string updatePartners(List<string> tminus, List<string> tplus,int taskId)
        {
            string sql = string.Empty;
            StringBuilder tlist = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            int cid=UserService.UcId();

            if (tminus.Count > 0)
            {
                sql = "delete from [CooPartnerlist] where cid={0} and  taskId={1} and Partner in ({2})";             
                foreach (string s in tminus)
                {
                    tlist.AppendFormat("'{0}',", s);
                }
                sql = string.Format(sql, cid, taskId,tlist.ToString().Trim(','));
            }
            
            foreach (string s in tplus)
            {
                sb.AppendFormat("insert into [CooPartnerlist](taskId,Partner,cid) values({0},'{1}',{2})", taskId, s, cid);               
            }

            sb.AppendFormat(" select Partner  from [CooPartnerlist] where cid={0} and taskId={1}",cid,taskId);
            sql = sql + sb.ToString();
            DataTable dt = DataProvider.GetDataTable(sql);
            string ret = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                ret += "," + dr["Partner"].ToString();
            }
            return ret.Trim(',');

        }


    }
}